package com.tool.cn.use.mysqlid;

import java.util.HashSet;
import java.util.Set;


/**
 * 
 * @author wangzonghui
 * @date 2020年6月22日 上午10:12:57 
 * @Description:雪花算法生成id实现类，功能待测试。单实例自增id，分布式框架20节点下使用uuid，20~200节点，自增加步长。200以上的借鉴Twitter雪花算法。
 */
public class IdWrodkTest {
	
	 static class IdWorkThread implements Runnable {

	        private Set<Long> set;

	        private IdWorker idWorker;

	 

	        public IdWorkThread(Set<Long> set, IdWorker idWorker) {

	            this.set = set;

	            this.idWorker = idWorker;

	        }

	 

	        public void run() {

	            while (true) {

	                long id = idWorker.nextId();

	                System.out.println("real id:" + id);

	                if (!set.add(id)) {

	                    System.out.println("duplicate:" + id);

	                }

	            }

	        }

	    }

	 

	    public static void main(String[] args) {

	        Set<Long> set = new HashSet<Long>();

	        final IdWorker idWorker1 = new IdWorker(0, 0);

	        final IdWorker idWorker2 = new IdWorker(1, 0);

	        Thread t1 = new Thread(new IdWorkThread(set, idWorker1));

	        Thread t2 = new Thread(new IdWorkThread(set, idWorker2));

	        t1.setDaemon(true);

	        t2.setDaemon(true);

	        t1.start();

	        t2.start();

	        try {

	            Thread.sleep(30000);

	        } catch (InterruptedException e) {

	            e.printStackTrace();

	        }

	    }

}
